package com.sctvcloud.zhaohua_sd.ui.activities;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;

import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.beans.ChooseCityBean;
import com.sctvcloud.zhaohua_sd.beans.ChooseCityVo;
import com.sctvcloud.zhaohua_sd.beans.CountryBean;
import com.sctvcloud.zhaohua_sd.beans.FCityState;
import com.sctvcloud.zhaohua_sd.beans.FCountyState;
import com.sctvcloud.zhaohua_sd.beans.NewsItem;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.adapter.ChooseCityAdapter;
import com.sctvcloud.zhaohua_sd.ui.dialog.ChooseCityFuncFragment;
import com.sctvcloud.zhaohua_sd.ui.utils.CityContrastUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sctvcloud.zhaohua_sd.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.sctvcloud.zhaohua_sd.ui.dialog.NetModeDiaFragment.OK_TAG;

public class ChooseCityActivity extends BaseActivity implements ChooseCityAdapter.OnItemClickListener, ChooseCityAdapter.OnCountyItemClickListener {

    @BindView(R.id.city_list)
    protected RecyclerView cityList;
    @BindView(R.id.title_top_back)
    protected ImageView backImg;
    @BindView(R.id.title)
    protected ImageView titleImg;
    @BindView(R.id.title_name)
    protected CustomFontTextView titleName;
    public static final String TITLE_KEY = "title_key";
    private ChooseCityAdapter adapter;
    private List<ChooseCityBean> citylist;
    private ChooseCityFuncFragment arouseAppFuncFragment;
    private ChooseCityFuncFragment toInstallFuncFragment;
    private static final String IS_START = "IS_START";
    public static final String NET_TAG = "chooseCityFuncFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        backImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        String title = getIntent().getStringExtra(TITLE_KEY);
        if (TextUtils.isEmpty(title)) {
            titleImg.setVisibility(View.VISIBLE);
            titleName.setVisibility(View.GONE);
        } else {
            titleImg.setVisibility(View.GONE);
            titleName.setVisibility(View.VISIBLE);
            titleName.setText("当前选择：" + title);
            titleName.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        }
        citylist = new ArrayList<>();
        getCityData();
//        stateList = CityContrastUtils.getInstance().getCityStatList();
        //创建LinearLayoutManager 对象 这里使用 LinearLayoutManager 是线性布局的意思
        LinearLayoutManager layoutmanager = new LinearLayoutManager(this);
        //设置RecyclerView 布局
        cityList.setLayoutManager(layoutmanager);

        adapter = new ChooseCityAdapter(this, citylist, title);
        cityList.setAdapter(adapter);
        adapter.setOnSubscribeClick(this, this);
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_choose_city);
        ButterKnife.bind(this);
    }


    private void getCityData() {
        String url = "sctv/cityConfig.json";
        NetUtils.getNetAdapter().getCityList(getOwnerName(), url, new AbsNetCallBack<ChooseCityVo>(ChooseCityVo.class) {
            @Override
            public void onSuc(ChooseCityVo vo) {
                if (null != vo && null != vo.getCitylist() && vo.getCitylist().size() > 0) {
                    citylist.addAll(vo.getCitylist());
                    adapter.setCityList(citylist);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }

    @Override
    public void onCityItemClick(ChooseCityBean cityState) {
        setResult(RESULT_OK);
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "选择市州"));
        GridsumWebDissector.getInstance().trackEvent(ChooseCityActivity.this, "", cityState.getCityName(), "", 200, pairs);
        if (cityState.getCityName().contains("四川观察") || cityState.getCityName().contains("成都")) {
            Cache.getInstance().setChoosedCity("");
            Cache.getInstance().setCityShow(false);
//                    ChooseCityActivity.this.finish();
        } else {
            Cache.getInstance().setChoosedCity(cityState.getCityName());
            Cache.getInstance().setStarted(false);
            if (cityState.isH5()) {
                Intent intent = new Intent(ChooseCityActivity.this, CityH5Activity.class);
                intent.putExtra(BaseActivity.EX_HTML, cityState.getUrl());
                startActivity(intent);
            }
            if (cityState.isSyncData()) {
                Cache.getInstance().setCityShow(true);
                Cache.getInstance().setChoosedCityNewsUrl(cityState.getInstitutionUrl());
                Cache.getInstance().setChoosedCityStUrl(cityState.getDomainName());
                Cache.getInstance().setChoosedCityTitle(cityState.getInstitutionName());
                Cache.getInstance().setChoosedCityIcon(cityState.getCityImage());
            } else {
                Cache.getInstance().setChoosedCityIcon("");
                Cache.getInstance().setChoosedCityTitle("");
                Cache.getInstance().setChoosedCityNewsUrl("");
                Cache.getInstance().setChoosedCityStUrl("");
                Cache.getInstance().setCityShow(false);
            }

            if (!cityState.isH5() && !cityState.isSyncData()) {
                Cache.getInstance().setCityShow(false);
                Cache.getInstance().setChoosedCity(cityState.getCityName());
                Intent intent = new Intent(ChooseCityActivity.this, CityStaHomepageActivity.class);
                intent.putExtra(BaseActivity.EX_ID, cityState.getInstitutionId());
                intent.putExtra(BaseActivity.EX_TITLE, cityState.getInstitutionName());
                intent.putExtra(CityStaHomepageActivity.INIT_SUBSCRIBE, true);
                intent.putExtra(CityStaHomepageActivity.HOT_TAG, 1);
                intent.putExtra(BaseActivity.EX_URL, cityState.getInstitutionUrl());
                startActivity(intent);
            }
//                    int save = (int) SharedPreferencesUtil.getParam(ChooseCityActivity.this, IS_START, 0);
//                    if (save == 2) {
//                        doStartApplicationWithPackageName();
//                    } else if (save == 1) {
//                    }else {
//                        showChooseStartAPP();
//                    }
        }
        ChooseCityActivity.this.finish();
    }

    @Override
    public void onCountyItemClick(CountryBean countyState) {
        setResult(RESULT_OK);
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "选择区县"));
        GridsumWebDissector.getInstance().trackEvent(ChooseCityActivity.this, "", countyState.getChildCityName(), "", 200, pairs);
//        Cache.getInstance().setCityShow(false);
//        Cache.getInstance().setChoosedCity(countyState.getChildCityName());
//        Intent intent = new Intent(ChooseCityActivity.this, CountyStatePageActivity.class);
//        intent.putExtra(BaseActivity.EX_ID, countyState.getChildInstitutionId());
//        intent.putExtra(BaseActivity.EX_TITLE, countyState.getChildInstitutionName());
//        intent.putExtra(CityStaHomepageActivity.INIT_SUBSCRIBE, true);
//        intent.putExtra(CityStaHomepageActivity.HOT_TAG, 1);
//        intent.putExtra(BaseActivity.EX_URL, countyState.getChildInstitutionUrl());
//        startActivity(intent);
//        ChooseCityActivity.this.finish();

        Cache.getInstance().setChoosedCity(countyState.getChildCityName());
        Cache.getInstance().setStarted(false);
        if (countyState.isChildIsH5()) {
            Intent intent = new Intent(ChooseCityActivity.this, CityH5Activity.class);
            intent.putExtra(BaseActivity.EX_HTML, countyState.getChildUrl());
            startActivity(intent);
        }
        if (countyState.isChildIsSyncData()) {
            Cache.getInstance().setCityShow(true);
            Cache.getInstance().setChoosedCityTitle(countyState.getChildInstitutionName());
            Cache.getInstance().setChoosedCityNewsUrl(countyState.getChildInstitutionUrl());
            Cache.getInstance().setChoosedCityStUrl(countyState.getChildDomainName());
            Cache.getInstance().setChoosedCityIcon(countyState.getChildCityImage());
        } else {
            Cache.getInstance().setChoosedCityIcon("");
            Cache.getInstance().setChoosedCityTitle("");
            Cache.getInstance().setChoosedCityStUrl("");
            Cache.getInstance().setCityShow(false);
        }

        if (!countyState.isChildIsH5() && !countyState.isChildIsSyncData()) {
            Cache.getInstance().setCityShow(false);
            Cache.getInstance().setChoosedCity(countyState.getChildCityName());
            Intent intent = new Intent(ChooseCityActivity.this, CityStaHomepageActivity.class);
            intent.putExtra(BaseActivity.EX_ID, countyState.getChildInstitutionId());
            intent.putExtra(BaseActivity.EX_TITLE, countyState.getChildInstitutionName());
            intent.putExtra(CityStaHomepageActivity.INIT_SUBSCRIBE, true);
            intent.putExtra(CityStaHomepageActivity.HOT_TAG, 1);
            intent.putExtra(BaseActivity.EX_URL, countyState.getChildInstitutionUrl());
            startActivity(intent);
        }
//                    int save = (int) SharedPreferencesUtil.getParam(ChooseCityActivity.this, IS_START, 0);
//                    if (save == 2) {
//                        doStartApplicationWithPackageName();
//                    } else if (save == 1) {
//                    }else {
//                        showChooseStartAPP();
//                    }

        ChooseCityActivity.this.finish();
    }


    private void showChooseStartAPP() {
        if (Cache.getInstance().isStarted()) {
            ChooseCityActivity.this.finish();
            return;
        }
        if (arouseAppFuncFragment == null) {
            arouseAppFuncFragment = new ChooseCityFuncFragment();
        }
        arouseAppFuncFragment.setDialogText("", "是否立即唤起“直播泸州APP”？");
        arouseAppFuncFragment.setDialogBtnText("暂不唤起", "唤起");
        arouseAppFuncFragment.setCallBack(chooseCallBack);
        arouseAppFuncFragment.show(getSupportFragmentManager(), NET_TAG);
    }

    //选择处理
    BaseDialogFragment.ICallBack chooseCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            boolean isRemind = (boolean) msg.obj;
            if (msg.what == NO_TAG) {
                JLog.e("chooseCityFuncFragment", "---取消");
                if (isRemind) {
                    SharedPreferencesUtil.setParam(ChooseCityActivity.this, IS_START, 1);
                }
                ChooseCityActivity.this.finish();
            } else if (msg.what == OK_TAG) {
                if (isRemind) {
                    SharedPreferencesUtil.setParam(ChooseCityActivity.this, IS_START, 2);
                }
                doStartApplicationWithPackageName();
            }
        }
    };

    /**
     * 唤起APP
     */
    private void doStartApplicationWithPackageName() {
        String packagename = "com.letv.app.ljodfh";
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
//            Toast.makeText(getContext(),"当前手机上未安装APP",Toast.LENGTH_LONG).show();
            showInstallAPP();
            return;
        }
        Intent intent = getPackageManager().getLaunchIntentForPackage(packagename);
        startActivity(intent);
        Cache.getInstance().setStarted(true);
        ChooseCityActivity.this.finish();
    }

    /**
     * 是否安装“直播泸州APP”
     */
    private void showInstallAPP() {
        if (toInstallFuncFragment == null) {
            toInstallFuncFragment = new ChooseCityFuncFragment();
        }
        toInstallFuncFragment.setDialogText("", "当前手机未安装，是否立即下载“直播泸州APP”？");
        toInstallFuncFragment.setDialogBtnText("暂不安装", "下载");
        toInstallFuncFragment.setDialogNotShowRemind();
        toInstallFuncFragment.setCallBack(netinstallCallBack);
        toInstallFuncFragment.show(getSupportFragmentManager(), NET_TAG);
    }

    //选择处理
    BaseDialogFragment.ICallBack netinstallCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            boolean isRemind = (boolean) msg.obj;
            if (msg.what == NO_TAG) {
                ChooseCityActivity.this.finish();
            } else if (msg.what == OK_TAG) {
                String downLoadAPPUrl = "http://imtt.dd.qq.com/16891/570AE512DA7AB67640A39172ECA57E4D.apk?fsname=com.letv.app.ljodfh_2.1.0_202.apk&csr=1bbd";
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(downLoadAPPUrl);
                intent.setData(content_url);
                startActivity(intent);
                ChooseCityActivity.this.finish();
            }
        }
    };

}
